var ZYRequestClient = require("../../../../utils/zy-request");
var requestClient;
var ZYSmartSealWX = require("../../../../utils/ZY_Minprogram_SDK_V1.0");
var zysealsdk;
const app = getApp();
Page({
  data:{
    deviceId:null,
    showSearch:false,
    mac:'',
    version:"2.0",
    connectStatus:false,
    checkStatus:false,
    sdkDevice:null,
    companyIndex: 0,
    companyList:[],
    departmentIndex: 0,
    departmentList:[],
    rules:[
      {
        name: 'mac',
        rules: [{required: true, message: '请搜索印章!'}]
      },
      {
        name: 'name',
        rules: [{required: true, message: '印章名称不能为空!'}]
      }
    ],
    formData:{},
    faceCheck:true,
    stampPhotoCheck:false,
    navbarData:{
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '添加印章', //导航栏 中间的标题
      white:true
     },
     // 导航头的高度
     height: app.globalData.height * 2 + 20
  },
  onLoad() {
    requestClient = new ZYRequestClient();
  },
  // 加载公司列表(只加载当前所在的公司)
  loadMyCompanyList(){
    var _this = this;
    var defaultCompany = wx.getStorageSync('defaultCompany');
    var companyList=[];
    if(defaultCompany){
      var company = {
        id:defaultCompany.id,
        name:defaultCompany.name
      };
      companyList.push(company);
      _this.setData({
        companyList:companyList
      });
      _this.loadDefaultCompany(companyList[0].id);
    }
  },
  // 加载公司一级部门
  loadDefaultCompany(companyId){
    var _this = this;
    requestClient.getCompanyResource(companyId,function(resource){
    _this.setData({
      departmentList:resource.data.data.departmentVoList
    });
  });
  },
  onShow(){
    var _this = this;
    zysealsdk = ZYSmartSealWX.getInstance({
      key:'C10E2A31D7B24E1B95DA3087C77DD22F'
    });
    _this.setData({
      companyList:[]
    });
    requestClient.checkFunctionPermission(1002,'您没有权限添加印章，请联系企业创建者！',function(){
      _this.loadMyCompanyList();
    },function(){
      wx.navigateBack({
        delta: 1,
      })
    });
  },
  onUnload(){
    this.disconnectDevice();
  },
  // 点击搜索印章
  bindSearchClick(e){
    var _this = this;
    // 判断是否有蓝牙权限
    wx.getSetting({
      success(res){
        if(res.authSetting["scope.bluetooth"]){
          _this.setData({
            showSearch:true,
            deviceId:null,
            checkStatus:false,
          });
          wx.showLoading({
            title: '正在搜索...',
            mask:true,
          })
          // 延时执行
          setTimeout(() => {
            _this.startDiscovery();
          }, 1500);
        } else {
          // 引导用户授权
          wx.authorize({
            scope: 'scope.bluetooth',
            success(){
              _this.setData({
                showSearch:true,
                deviceId:null,
                checkStatus:false,
              });
              wx.showLoading({
                title: '正在搜索...',
                mask:true,
              })
              // 延时执行
              setTimeout(() => {
                _this.startDiscovery();
              }, 1500);
            },
            fail(){
              // 引导用户打开设置
              wx.showModal({
                title:"蓝牙权限",
                content:'需要使用您的蓝牙搜索和启动印章',
                success(r){
                  if(r.confirm){
                    wx.openSetting({
                      success(res){
                        if(res.authSetting["scope.bluetooth"]){
                          _this.setData({
                            showSearch:true,
                            deviceId:null,
                            checkStatus:false,
                          });
                          wx.showLoading({
                            title: '正在搜索...',
                            mask:true,
                          })
                          // 延时执行
                          setTimeout(() => {
                            _this.startDiscovery();
                          }, 1500);
                        } else {
                          wx.showToast({
                            title: '暂无蓝牙权限',
                          })
                        }
                      }
                    })
                  }
                }
              })
            }
          })
        }
      }
    })
  },
  // 开始搜索
  startDiscovery:function(){
    wx.hideLoading({
      success: (res) => {},
    })
    var _this = this;
    // 先关闭连接
    _this.disconnectDevice(_this._startDiscovery);
  },
  _startDiscovery(){
    var _this = this;
    zysealsdk.startDiscovery(function(res){
      if(_this.data.deviceId != null){
        return;
      }
      // 先停止搜素
      _this.stopDiscovery();
      if(res.result){
        var device = res.data;
        // 赋值
        _this.setData({
          deviceId:device.deviceId,
          mac:device.mac,
          [`formData.mac`]:device.mac,
        });
        // 获取注册设备，验证所属平台
        requestClient.getAccessDevice(_this.data.mac,function(resData){
          _this.setData({
          sdkDevice:resData.data.data
          });
          if(resData.data.success){
            var sdkDevice = resData.data.data;
            if(sdkDevice.sdkId == 8){
              // 连接印章
              // _this.connectDevice();
              // 判断是否添加过
              requestClient.getSealInfoByMac(_this.data.mac,function(res){
                if(res.data.data && res.data.data.enableFlag){
                  wx.showToast({
                    title: '此印章已被绑定',
                    icon:'error'
                  })
                  setTimeout(() => {
                    wx.navigateTo({
                      url: '../sealinfo/index?id=' + res.data.data.id + '&editable=false',
                    })
                  }, 1500);
                } else {
                  // 连接印章
                  _this.connectDevice();
                }
              });
            } else {
              wx.showModal({
                title:'注册失败',
                content:'此印章不属于鑫泽科智能印章平台(101)！',
                showCancel:false,
                success(r){
                }
              })
            }
          } else {
            wx.showModal({
              title:'注册设备',
              content:'您确定要将此印章绑定到鑫泽科智能印章平台吗？',
              success(r){
                if(r.confirm){
                  // 连接印章
                  _this.connectDevice();
                }
              }
            })
          }
        });
      } else {
        wx.showModal({
          title:'搜索失败',
          content:res.message,
          showCancel:false,
          success(r){
  
          }
        })
      }
    });
  },
  // 停止搜索
  stopDiscovery(e){
    var _this = this;
    _this.setData({
      showSearch:false
    });
    zysealsdk.stopDiscovery();
  },
  // 连接设备
  connectDevice(){
    var _this = this;
    var deviceId = _this.data.deviceId;
    if(deviceId == null){
      return;
    }
    wx.showLoading({
      title: '正在连接..',
      mask:true,
    })
    // 连接印章
    zysealsdk.connectDevice(deviceId,_this.onConnectStatusChanged);
    // 连接超时提示重连
    setTimeout(() => {
      if(!_this.data.connectStatus){
        wx.hideLoading({
          success: (res) => {},
        });
        wx.showToast({
          title: '连接失败,可以重新搜索！',
          icon:'none'
        });
      }
    }, 3000);
  },
  // 连接状态回调
  onConnectStatusChanged(res){
    var _this = this;
    if(res.data.connectStatus){
      _this.setData({
        connectStatus:true
      });
      // 延时验证密钥
      setTimeout(() => {
        zysealsdk.check(_this.onCheckCallBack)
      }, 2000);
    } else {
      _this.setData({
        connectStatus:false
      });
    }
  },
  // 密钥验证事件回调
  onCheckCallBack(dataResult){
    var _this = this;
    wx.hideLoading({
      success: (res) => {},
    })
    _this.setData({
      version:dataResult.data.version,
    });
    // 判断验证结果
    if(dataResult.result){
      _this.setData({
        checkStatus:true,
      });
      wx.showToast({
        title: dataResult.message,
        icon:'none'
      })
    } else {
      if(_this.data.sdkDevice == null){
        wx.showModal({
          title:'注册失败',
          content:"此印章不属于鑫泽科智能印章平台(102)！",
          showCancel:false,
          success(r){
          }
        })
      } else {
        if(_this.data.sdkDevice.allowReset){
          wx.showLoading({
            title: '正在重置设备',
            mask:true,
          })
         // 超级密验证
          zysealsdk.checkByKey('2BFBF7DA7B2F11EB998B18C04D73E7B2',function(res){
            wx.hideLoading({
              success: (res) => {},
            })
            _this.setData({
              version:dataResult.data.version,
            });
            if(res.result){
              // 重置设备
              zysealsdk.resetDevice(function(res){
                if(res.result){
                  _this.setData({
                    checkStatus:true,
                  });
                  wx.showToast({
                    title: '重置成功！',
                    icon:'none'
                  })
                } else {
                  wx.showToast({
                    title: '重置失败！102',
                    icon:'none'
                  })
                }
              });
            } else {
              wx.showToast({
                title: '重置失败！101',
                icon:'none'
              })
            }
          })
        } else {
          wx.showModal({
            title:'注册失败',
            content:"此印章不属于鑫泽科智能印章(103)！",
            showCancel:false,
            success(r){
            }
          })
        }
      }
    }
  },
  // 断开设备
  disconnectDevice(callback){
    var _this = this;
    _this.setData({
      connectStatus:false,
    });
    wx.hideLoading({
      success: (res) => {},
    })

    zysealsdk.disConnectDevice();
    if(callback){
      callback();
    }
  },
  formInputChange(e) {
    const {field} = e.currentTarget.dataset;
    this.setData({
        [`formData.${field}`]: e.detail.value
    })
  },
  // 选择公司
  bindCompanyChange(e){
    this.setData({
      companyIndex: parseInt(e.detail.value)
    });
    this.loadDefaultCompany(this.data.companyList[this.data.companyIndex].id);
  },
  // 选择部门
  bindDepartmentChange(e){
    this.setData({
      departmentIndex: parseInt(e.detail.value)
    });
  },
  // 盖章前确认用印人
  bindFaceChange(e){
    var _this = this;
    _this.setData({
      faceCheck:e.detail.value,
    });
  },
  // 盖章时自动拍照
  bindStampPhotoChange(e){
    var _this = this;
    _this.setData({
      stampPhotoCheck:e.detail.value,
    });
  },
  submitForm(e){
    var _this = this;
    _this.selectComponent('#form').validate((valid, errors) => {
          if (!valid) {
              const firstError = Object.keys(errors)
              if (firstError.length) {
                // 提示用户
                wx.showToast({
                  title: errors[firstError[0]].message,
                  icon:'none'
                })
              }
          } else {
           // 判断是否选中公司
            var companyList = _this.data.companyList;
            if(companyList.length == 0){
              // 提示用户
              wx.showToast({
                title: '请选择公司',
                icon:'none'
              })
              return;
            }
            // 判断是否选择部门
            var departmentList = _this.data.departmentList;
            if(departmentList.length == 0){
              // 提示用户
              wx.showToast({
                title: '请选择部门',
                icon:'none'
              })
              return;
            }
            // 构造印章数据
            var userInfo = wx.getStorageSync('userInfo');
            var sealData = {
              name:_this.data.formData.name,
              mac:_this.data.mac,
              createUser:userInfo.id,
              companyId:_this.data.companyList[_this.data.companyIndex].id,
              departmentId:_this.data.departmentList[_this.data.departmentIndex].id,
              facePhoto:_this.data.faceCheck,
              forcePhotograph:_this.data.stampPhotoCheck,
              version:_this.data.version,
            };
            wx.showModal({
              title:'添加印章',
              content:'您确定将此印章添加到' + _this.data.companyList[_this.data.companyIndex].name + '吗？',
              success(s){
                  if(s.confirm){
                    requestClient.checkFunctionPermission(1002,'您没有权限添加印章，请联系企业创建者！',function(){
                        requestClient.addSeal(sealData,function(res){
                          if(res.data.code == 1){
                            wx.showToast({
                              title: '添加成功！',
                              icon:"none",
                              mask:true,
                              duration:2000
                            })
                            setTimeout(() => {
                              wx.navigateBack({
                                delta: 1,
                              })
                            }, 2000);
                          } else {
                            wx.showToast({
                              title: res.data.msg,
                              icon:'none'
                            })
                            if(res.data.code == 2002){
                              setTimeout(() => {
                                requestClient.getSealInfoByMac(_this.data.mac,function(resData){
                                  wx.navigateTo({
                                    url: '../sealinfo/index?id=' + resData.data.data.id + '&editable=false',
                                      })
                                })
                              }, 1500);
                            }
                          }
                        });
                    },function(){
                      wx.navigateBack({
                        delta: 1,
                      })
                    });
                  }
              }
            })
          }
      })
  }
})